package com.yxkj.syh.app.huarong.activities.orders.detail.status_other;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.lcw.library.imagepicker.ImagePicker;
import com.syh.app.basic.base.BaseActivity;
import com.syh.app.basic.bean.LiveDataEvent;
import com.syh.app.basic.config.BasicConstants;
import com.syh.app.basic.utils.AppUtil;
import com.syh.app.basic.utils.ComUtil;
import com.syh.app.basic.utils.PermissionUtil;
import com.syh.app.basic.utils.Tooast;
import com.syh.app.basic.utils.imagepickerhelper.ImagePickerHelper;
import com.syh.app.basic.views.ImageWatcher;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yxkj.syh.app.huarong.BR;
import com.yxkj.syh.app.huarong.R;
import com.yxkj.syh.app.huarong.adps.AddedGoodsAdp;
import com.yxkj.syh.app.huarong.bean.CheckInfo;
import com.yxkj.syh.app.huarong.bean.Goods;
import com.yxkj.syh.app.huarong.bean.OrderInfo;
import com.yxkj.syh.app.huarong.constants.ArouterPath;
import com.yxkj.syh.app.huarong.constants.OrderStatus;
import com.yxkj.syh.app.huarong.databinding.ActivityOrderOtherStatusBinding;
import com.yxkj.syh.app.huarong.util.PhotoUtil;
import com.yxkj.syh.app.huarong.util.UserManager;
import com.yxkj.syh.app.huarong.views.FinishOrderDialog;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.List;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

@Route(path = ArouterPath.ORDER_OTHER_STATUS_ACTIVITY)
public class OrderOtherStatusActivity extends BaseActivity<ActivityOrderOtherStatusBinding, OrderOtherStatusVM> {
    public static final int PERMISSION_IMAGE = 0xb12;

    @Autowired
    long orderId;

    private AddedGoodsAdp mAddedGoodsAdp;
    private FinishOrderDialog mFinishOrderDialog;

    @Override
    protected int getContentLayout() {
        return R.layout.activity_order_other_status;
    }

    @Override
    protected int getViewModelId() {
        return BR.orderOtherStatusVM;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        if (orderId <= 0) finish();
        mVDBinding.titleView.setLeftOnClickListener(v -> finish());

        mAddedGoodsAdp = new AddedGoodsAdp();
        mVDBinding.rvGoods.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        mVDBinding.rvGoods.setAdapter(mAddedGoodsAdp);
        mAddedGoodsAdp.setEditAble(false);

        mVDBinding.tvCopyNo.setOnClickListener(v -> {
            if (AppUtil.copy2Clipboard(OrderOtherStatusActivity.this, mViewModel.mldOrderDetail.getValue().getNo())) {
                Tooast.success("运单编号已复制到粘贴板");
            }
        });

        mVDBinding.btnConfirm.setOnClickListener(v -> {
            OrderInfo orderInfo = mViewModel.mldOrderDetail.getValue();
            if (orderInfo != null) {
                if (orderInfo.getStatus() == OrderStatus.ALREADY_SHIPMENTS) {//运输中
                    if (orderInfo.getIsEmpty() == 0) {
                        finishOrder();
                    } else {
                        mViewModel.orderFinish(null);
                    }
                } else if (orderInfo.getStatus() >= OrderStatus.ALREADY_RECEIVING) {//已签收
                    applyPayOrder();
                }
            }
        });


    }

    @Override
    protected void initData() {
        mViewModel.getOrderDetail(orderId);
    }

    @Override
    protected void initObservers() {
        super.initObservers();
        mViewModel.mldOrderDetail.observe(this, orderInfo -> {
            mViewModel.ofLineType.set(orderInfo.getLineType() == 0 ? "直达" : "回头车");
            mViewModel.ofFromAddress.set(orderInfo.getStartArea() + orderInfo.getStartAddress());
            mViewModel.ofToAddress.set(orderInfo.getEndArea() + orderInfo.getEndAddress());
            mViewModel.ofCarHeadNo.set(orderInfo.getCarNo());
            mViewModel.ofCarTrailerNo.set(orderInfo.getSemitrailerNo());
            mViewModel.ofOrderNo.set(orderInfo.getNo());
            mViewModel.ofCreatTime.set(orderInfo.getCreateTime());
            mViewModel.ofRemrk.set(orderInfo.getRemark());

            if (orderInfo.getStatus() == OrderStatus.ALREADY_SHIPMENTS) {//运输中
                mViewModel.ofStatusText.set("运输中");
                mViewModel.ofFacheTime.set(mViewModel.getOrderTime(1));
                mViewModel.ofButtonText.set("签收");
            } else if (orderInfo.getStatus() >= OrderStatus.ALREADY_RECEIVING) {//已签收
                if (!UserManager.getUserManager().getUser().getEmpId().equals(BasicConstants.WAIDIAOSIJI_EMPID)) {//外吊车不能申请支出单
                    if (orderInfo.getExpensesExists() == 0 && orderInfo.getLineType() == 0 && orderInfo.getStatus() >= OrderStatus.ALREADY_RECEIVING) {
                        mViewModel.ofButtonText.set("申请支出单");
                    }
                }
                mViewModel.ofStatusText.set("已签收");
                mViewModel.ofFacheTime.set(mViewModel.getOrderTime(1));
                mViewModel.ofFinishTime.set(mViewModel.getOrderTime(2));
            } else if (orderInfo.getStatus() == OrderStatus.ALREADY_INVALID) {//已取消
                mViewModel.ofStatusText.set("已取消");
            }
            setGoods(orderInfo.getOrderProductList());
            if (orderInfo.getStatus() == OrderStatus.ALREADY_SHIPMENTS) {//运输中

                //收货单(发)
                List<String> shdfUrls = mViewModel.getLogCredentials(1, 1);
                if (shdfUrls.size() > 0) mViewModel.ofHasShdfUrl.set(true);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ComUtil.Dp2Px(this, 70), ComUtil.Dp2Px(this, 70));
                params.rightMargin = ComUtil.Dp2Px(this, 10);
                int size = shdfUrls.size() > 6 ? 6 : shdfUrls.size();
                for (int i = 0; i < size; i++) {
                    ImageView iv = new ImageView(this);

                    String url = shdfUrls.get(i);
                    Glide.with(this).load(url).apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.NONE))
                            .into(iv);
                    mVDBinding.llShdfCertificates.addView(iv, params);
                    iv.requestLayout();
                    iv.setOnClickListener(v -> new ImageWatcher(OrderOtherStatusActivity.this).show(url));
                }

            } else if (orderInfo.getStatus() == OrderStatus.ALREADY_INVALID) {//已取消
                mVDBinding.flStatus.setBackgroundColor(Color.parseColor("#DBDFE1"));
                mVDBinding.tvStatus.setTextColor(ContextCompat.getColor(OrderOtherStatusActivity.this, R.color.textColor4));
            } else if (orderInfo.getStatus() >= OrderStatus.ALREADY_RECEIVING) {//已签收 及大于2的状态

                //收货单(发)
                List<String> shdfUrls = mViewModel.getLogCredentials(1, 1);
                if (shdfUrls.size() > 0) mViewModel.ofHasShdfUrl.set(true);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ComUtil.Dp2Px(this, 70), ComUtil.Dp2Px(this, 70));
                params.rightMargin = ComUtil.Dp2Px(this, 10);
                int size = shdfUrls.size() > 6 ? 6 : shdfUrls.size();
                for (int i = 0; i < size; i++) {
                    ImageView iv = new ImageView(this);

                    String url = shdfUrls.get(i);
                    Glide.with(this).load(url).apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.NONE))
                            .into(iv);
                    mVDBinding.llShdfCertificates.addView(iv, params);
                    iv.requestLayout();
                    iv.setOnClickListener(v -> new ImageWatcher(OrderOtherStatusActivity.this).show(url));
                }

                //收货单(收)
                List<String> shdsUrls = mViewModel.getLogCredentials(2, 1);
                if (shdsUrls.size() > 0) mViewModel.ofHasShdsUrl.set(true);
                LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams(ComUtil.Dp2Px(this, 70), ComUtil.Dp2Px(this, 70));
                params2.rightMargin = ComUtil.Dp2Px(this, 10);
                int size2 = shdsUrls.size() > 6 ? 6 : shdsUrls.size();
                for (int i = 0; i < size2; i++) {
                    ImageView iv = new ImageView(this);

                    String url = shdsUrls.get(i);
                    Glide.with(this).load(url).apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.NONE))
                            .into(iv);
                    mVDBinding.llShdsCertificates.addView(iv, params2);
                    iv.requestLayout();
                    iv.setOnClickListener(v -> new ImageWatcher(OrderOtherStatusActivity.this).show(url));
                }

            }

        });

        mViewModel.mldImageUrl.observe(this, s -> {
            mFinishOrderDialog.setImageUrl(s);
        });

        mViewModel.mldFinishOrder.observe(this, aBoolean -> {
            if (aBoolean) {
                if (mFinishOrderDialog != null && mFinishOrderDialog.isShowing())
                    mFinishOrderDialog.cancel();
                EventBus.getDefault().post(new LiveDataEvent(BasicConstants.EVENT_SELECT_ORDER_ALL));
                finish();
            }
        });

        mViewModel.mldApplyPayOrder.observe(this, aBoolean -> {
            if (aBoolean) {
                finish();
            }
        });

    }

    private void setGoods(List<Goods> goods) {
        for (Goods temp : goods) {
            temp.setAdded(true);
            temp.setLableStatus(0);
            temp.setQuantity(temp.getWeight());
        }
        mAddedGoodsAdp.setNewData(goods);
    }

    /**
     * 签收
     */
    private void finishOrder() {
        if (mFinishOrderDialog == null) {
            mFinishOrderDialog = new FinishOrderDialog(this, new FinishOrderDialog.Listener() {
                @Override
                public void onUpload() {
                    AndPermission.with(OrderOtherStatusActivity.this).requestCode(PERMISSION_IMAGE)
                            .permission(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            .callback(mPermissionListener).start();
                }

                @Override
                public void onCommit(List<String> url) {
                    mViewModel.orderFinish(url);
                }
            });
        }
        if (!mFinishOrderDialog.isShowing())
            mFinishOrderDialog.show();
    }

    /**
     * 申请支出单
     */
    private void applyPayOrder() {
        if (mViewModel.mldOrderDetail.getValue() == null) return;
        new AlertDialog.Builder(this).setMessage("是否立即申请？")
                .setNegativeButton("暂不申请", null)
                .setPositiveButton("立即申请", (dialog, which) -> {
                    mViewModel.applyPayOrder();
                }).create().show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == ImagePickerHelper.REQUEST_SELECT_IMAGES_CODE) {
                List<String> imagePaths = data.getStringArrayListExtra(ImagePicker.EXTRA_SELECT_IMAGES);
                Luban.with(this).load(imagePaths.get(0))
                        .setTargetDir(AppUtil.getLubanPath())
                        .ignoreBy(100)
                        .setCompressListener(new OnCompressListener() {
                            @Override
                            public void onStart() {
                                showLoading("Compress");
                            }

                            @Override
                            public void onSuccess(File file) {
                                hideLoading("Compress");
                                mViewModel.uploadImage(file);
                            }

                            @Override
                            public void onError(Throwable e) {
                                hideLoading("Compress");
                                Tooast.normalInfo("压缩图片错误");

                            }
                        }).launch();
            } else if (requestCode == PhotoUtil.GET_IMAGE_BY_CAMERA) {
                File imageFile;
                if (Build.VERSION.SDK_INT >= 19) {
                    imageFile = ComUtil.getUriFromKitKat(this, PhotoUtil.imageUriFromCamera);
                } else {
                    imageFile = ComUtil.getUriBeforeKitKat(this, PhotoUtil.imageUriFromCamera);
                }
                if (imageFile.length() > 1 * 1024 * 1024) {
                    Luban.with(this).load(imageFile)
                            .setTargetDir(AppUtil.getLubanPath())
                            .ignoreBy(100)
                            .setCompressListener(new OnCompressListener() {
                                @Override
                                public void onStart() {
                                    showLoading("Compress");
                                }

                                @Override
                                public void onSuccess(File file) {
                                    hideLoading("Compress");
                                    mViewModel.uploadImage(file);
                                }

                                @Override
                                public void onError(Throwable e) {
                                    hideLoading("Compress");
                                    Tooast.normalInfo("压缩图片错误");

                                }
                            }).launch();
                } else {
                    mViewModel.uploadImage(imageFile);
                }
            }
        }
    }


    private void startImageLib() {
        ImagePickerHelper.startImagePicker(this);
    }

    private PermissionListener mPermissionListener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            if (requestCode == PERMISSION_IMAGE) {
                new AlertDialog.Builder(OrderOtherStatusActivity.this).setItems(new String[]{"相册", "拍照"}, (dialog, which) -> {
                            dialog.cancel();
                            if (which == 0) {
                                startImageLib();
                            } else if (which == 1) {
                                PhotoUtil.openCameraImage(OrderOtherStatusActivity.this);
                            }
                        }
                ).create().show();
            }
        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            if (requestCode == PERMISSION_IMAGE) {
                PermissionUtil.with(OrderOtherStatusActivity.this)
                        .addPermission(Manifest.permission.CAMERA)
                        .addPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
                        .addPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .initPermission();
            }
        }
    };

}
